<script setup lang="ts">
import dayjs from 'dayjs'
import { useRequest } from 'vue-request'
import { fetchTakedOrdersAPI } from '@/apis/fetchTakedOrders'
import { useUserInfoStore } from '@/store/userInfo'
import { useDriverStatusStore } from '@/store/driverStatus'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const driverStatusStore = useDriverStatusStore()

const pTabConfiguration = ['快车订单', '代叫订单', '捎件订单']
const selectedPTabIndex = ref(0)

const tabConfiguration = ['已接单', '进行中', '已完成', '已取消']
const selectedTabIndex = ref(0)

const { data, loading, refresh } = useRequest(
  () => fetchTakedOrdersAPI({
    ...driverStatusStore.location,
    type: `${selectedPTabIndex.value + 1}`,
    driver_status: `${selectedTabIndex.value + 1}`,
  }, userInfoStore.userInfo!.token).then(res => res.data?.data),
  { manual: true },
)

onLoad(async () => {
  await driverStatusStore.updateLocation()
  refresh()
})
watch(selectedPTabIndex, () => {
  selectedTabIndex.value === 0 ? refresh() : selectedTabIndex.value = 0
})
watch(selectedTabIndex, () => refresh())

function handleViewOrderDetail(id: string) {
  router.push({
    name: 'orderDetail',
    params: { id },
  })
}
</script>

<template>
  <view class="bg-white">
    <view class="flex items-center">
      <view
        v-for="tab, index in pTabConfiguration"
        :key="index"
        class="flex flex-1 items-center justify-center"
        @tap="selectedPTabIndex = index"
      >
        <view
          class="my-16rpx rounded-full px-14rpx py-18rpx"
          :class="index === selectedPTabIndex ? 'bg-#3F8BF6 text-white font-semibold' : ''"
        >
          {{ tab }}
        </view>
      </view>
    </view>
    <Tabs
      :items="tabConfiguration"
      :selected-index="selectedTabIndex"
      @change="i => selectedTabIndex = i"
    />
  </view>
  <view class="p-24rpx">
    <view v-if="data?.length === 0" class="h-400rpx flex items-center justify-center text-28rpx text-#999999">
      暂无订单
    </view>
    <OrderCard
      v-for="item in data"
      :key="item.id"
      :order-id="item.id.toString()"
      :order-type="item.type"
      :order-status="item.driver_status"
      :price="item.money"
      :time="dayjs(item.create_time).format('YYYY-MM-DD HH:mm')"
      :distance="item.distance"
      :from="item.start_place"
      :to="item.end_place"
      @tap="handleViewOrderDetail(item.id.toString())"
    />
  </view>

  <view v-if="!data?.length" class="absolute left-1/2 top-1/2 text-28rpx text-#999999 -translate-1/2">
    暂无数据
  </view>
  <uv-loading-page :loading="loading" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'orders'
style:
  navigationBarTitleText: '订单管理'
</route>
